#include "modbus.h"
#include "device_usart.h"
#include <stdlib.h>
#include <stdio.h>
#include "string.h"
#include "infoblock.h"

#ifndef _STR
#define __STR(x)                    #x
#define _STR(x)                     __STR(x)
#endif
#define REVISION_STRING             "V" _STR(APP_FW_VERSION_HIGH) "." _STR(APP_FW_VERSION_LOW) " "

#define OBJECT_VENDOR_NAME          0x00
#define OBJECT_PRODUCT_CODE         0x01
#define OBJECT_REVISION             0x02
#define OBJECT_COUNT                3


typedef struct DEVICE_OBJECT
{
    uchar id;
    char *val;
} DEVICE_OBJECT;

DEVICE_OBJECT object[OBJECT_COUNT] =
{
    OBJECT_VENDOR_NAME,     "Zonci",
    OBJECT_PRODUCT_CODE,    "0003",
    OBJECT_REVISION,        REVISION_STRING,
};

const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
char date_s[20];

void getdate(void)
{
  char temp [] = __DATE__;  /*__DATA__ format: Nov 08 2000 replace by 11 08 2000*/
  unsigned char i;
  unsigned char month, day;
  unsigned short year;

  year = atoi(temp + 6);
  *(temp + 6) = 0;
  day = atoi(temp + 4);
  *(temp + 3) = 0;
  for (i = 0; i < 12; i++)
  {
    if (!strcmp(temp, months[i]))
    {
      month = i + 1;
      date_s[0] = 0;
      sprintf(date_s, "%s %02d/%02d/%02d",REVISION_STRING, month,day,year);
      object[2].val = date_s;
      return;
    }
  }
}

void Read_Identification(void)
{
    uchar n, len;
//    getdate();

    // 查找匹配的ID
    for(n = 0; n < OBJECT_COUNT; ++n)
        if (object[n].id == uart0_buf[4])
            break;

    if (n >= OBJECT_COUNT)
        n = 0;

    // 单个访问时, 指定的ID不存在
    if (uart0_buf[3] == 4 && object[n].id != uart0_buf[4])
    {
        Exception_Response(ILLEGAL_DATA_ADDRESS);
        return;
    }

    uart0_buf[4] = 0x83;        // 符合级
    uart0_buf[5] = 0x00;        // 更多数据
    uart0_buf[6] = 0x00;        // 下一对象ID
    uart0_buf[7] = uart0_buf[3] == 4 ? 1 : OBJECT_COUNT;        // 对象数量

    uart0_len = 8;
    for(; n < OBJECT_COUNT; ++n)
    {
        len = strlen(object[n].val);
        if (uart0_len + len + 4 >= UART0_BUF_SIZE)
        {
            uart0_buf[5] = 0xFF;                // 更多数据
            uart0_buf[6] = object[n].id;        // 下一对象ID
            break;
        }
        uart0_buf[uart0_len++] = object[n].id;
        uart0_buf[uart0_len++] = len;
        strcpy((char*)(uart0_buf+uart0_len), object[n].val);
        uart0_len += len;
    }
    Response();
}
